import cheerio from "cheerio";
import {eventHandler,EventCode} from "../event/eventHandler.js"
import { iArg } from "../iArg";
import { iFetcher } from "../iFetcher";
import { fetchRawData } from "./fetchRawData.js";

class CompetitionHistoryFetcher implements iFetcher {
  public data: competitionHistory[] = [];
  public async fetch(arg: iArg): Promise<string> {
    const { userName } = arg;
    let htmlText: string = "";
    let requestUrl = `https://atcoder.jp/users/${userName}/history`
    htmlText = await fetchRawData(requestUrl)
    if (htmlText === "") {
      return ""
    }
    

    try {
      let $ = cheerio.load(htmlText)("tbody").find("tr");
      if ($.length === 0) {
        throw new Error()
      }

      for (let i = 0; i < $.length; i++) {
        this.data.push(
          new competitionHistory(
            $.eq(i).find("td").eq(0).text(),
            $.eq(i).find("td").eq(1).find("a").eq(0).text(),
            $.eq(i).find("td").eq(2).text(),
            $.eq(i).find("td").eq(3).text(),
            $.eq(i).find("td").eq(4).text(),
            $.eq(i).find("td").eq(5).text(),
            $.eq(i).find("td").eq(1).find("a").eq(0).attr("href") as string
          )
        );
      }
    } catch (e) {
      if (e instanceof Error) {
        eventHandler.handle(EventCode.PAESE_RAW_DATA_EXCEPTION,
          `parse data from ${requestUrl} err`, new Error()
        )
      }
    }


    return JSON.stringify(this.data);
  }
}
class competitionHistory {
  constructor(
    date: string = "",
    contest: string = "",
    rank: string = "",
    performace: string = "",
    newRating: string = "",
    diff: string = "",
    contestUrl: string = ""
  ) {
    this.Date = Date.parse(date);
    this.Contest = contest;
    this.Rank = rank;
    this.Performace = performace;
    this.NewRating = newRating;
    this.Diff = diff;
    this.ContestUrl = "https://atcoder.jp" + contestUrl;
  }
  Date: number;
  Contest: string;
  ContestUrl: string;
  Rank: string;
  Performace: string;
  NewRating: string;
  Diff: string;
}


export { CompetitionHistoryFetcher };
